package business_logic.view;

import java.awt.Graphics;
import java.awt.image.BufferedImage;

import fiuba.algo3.titiritero.modelo.SuperficieDeDibujo;
import fiuba.algo3.titiritero.dibujables.SuperficiePanel;

import business_logic.Tile;

public class ReduceAnimation implements Animation
{

    static final int FRAMES_PER_STEP = 3; // TODO: hacer esto configurable...
    Image m_originalImage;
    int m_lastStep;
    int m_currentStep;
    int m_framesDrawInCurrentStep;
    
    double m_scaleFactor;
    int m_scaledWidth;
    int m_scaledHeight;
    private int m_xOffset;
    private int m_yOffset;
    
    ReduceAnimation( Image image, int steps )
    {
        m_originalImage = image;
        m_lastStep = steps;
        
        initialize();
    }
    
    public void draw(int x, int y, SuperficieDeDibujo graphicSurface)
    {
        if ( isDone() )
        {
            return;
        }
        else
        {            
            
            // TODO: Revisar el algoritmo de escalado
            // TODO: intentar mantener el aspect ratio de la imagen
            Graphics g = ((SuperficiePanel)graphicSurface).getBuffer();
            
            BufferedImage image = m_originalImage.getBufferedImage();
            
            g.drawImage( image, x+m_xOffset, y+m_yOffset, m_scaledWidth, m_scaledHeight, null );
            
            
            // Indico que se pasa al siguiente Step (si ya dibuje los frames del step anterior) y re-escalo
            if ( m_framesDrawInCurrentStep < FRAMES_PER_STEP )
            {
                m_currentStep++;
                m_framesDrawInCurrentStep=0;
                
                // Escalo la imagen a la mitad y hago que su ancho y alto sean un valor par (para facilitar el centrado)
                m_scaledWidth = (int)(Math.ceil(m_scaledWidth*m_scaleFactor)+Math.ceil(m_scaledWidth*m_scaleFactor)%2);
                m_scaledHeight = (int)(Math.ceil(m_scaledHeight*m_scaleFactor)+Math.ceil(m_scaledHeight*m_scaleFactor)%2);
                
                
                // TODO: Crear alguna tool qsea centrar en tile.
                m_xOffset = (int)Tile.getSize()/2-m_scaledWidth/2;;
                m_yOffset = (int)Tile.getSize()/2-m_scaledHeight/2;;
            }
            else
            {
                m_framesDrawInCurrentStep++;
            }
        }
    }

    public boolean isDone()
    {
        if ( m_currentStep < m_lastStep )
            return false;
        else
            return true;
    }
    
    public void restart()
    {
        initialize();
    }
    
    private void initialize()
    {
        m_currentStep = 0;
        m_framesDrawInCurrentStep = 0;
        
        m_scaledWidth = m_originalImage.getBufferedImage().getWidth();
        m_scaledHeight = m_originalImage.getBufferedImage().getHeight();
        
        m_xOffset = 0;
        m_yOffset = 0;
        
        m_scaleFactor = 0.5;
        
    }
}
